<template>
  <div class="login-container">
    <el-card class="login-card">
      <div slot="header">
        <h2>用户登录</h2>
      </div>
      <el-form :model="loginForm" :rules="rules" ref="loginForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="loginForm.username" name="username" placeholder="请输入用户名" aria-label="用户名" title="用户名"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="loginForm.password" name="password" type="password" placeholder="请输入密码" aria-label="密码" title="密码"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleLogin" :loading="loading" aria-label="登录" title="登录">登录</el-button>
          <el-button @click="handleRegister" aria-label="注册" title="注册">注册</el-button>
        </el-form-item>
      </el-form>
      <div v-if="errorMessage" class="error-message" role="alert">
        {{ errorMessage }}
      </div>
    </el-card>
  </div>
</template>

<script>
import { login } from '@/services/user'
import qs from 'qs'

export default {
  name: 'Login',
  data() {
    return {
      loginForm: {
        username: '',
        password: ''
      },
      loading: false,
      errorMessage: '', // 添加错误信息显示
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    // 页面加载时清除可能存在的认证信息
    this.clearAuthData();
  },
  methods: {
    clearAuthData() {
      // 清除所有认证相关数据
      localStorage.removeItem('isAuthenticated');
      localStorage.removeItem('token');
    },
    
    async handleLogin() {
      this.loading = true;
      this.errorMessage = ''; // 清除之前的错误信息
      try {
        const valid = await this.$refs.loginForm.validate()
        if (valid) {
          try {
            const response = await login(this.loginForm)
            console.log('登录响应:', response)
            
            // 成功登录，存储用户信息和token到本地存储
            this.$message.success('登录成功')
            localStorage.setItem('isAuthenticated', 'true')
            if (response && response.token) {
              localStorage.setItem('token', response.token)
            }
            this.$router.push('/home')
          } catch (error) {
            console.error('登录错误:', error)
            // 处理网络错误或服务器无响应的情况
            if (error.code === 'ERR_NETWORK') {
              this.errorMessage = '无法连接到服务器，请检查网络连接或联系管理员'
            } else if (error.response) {
              // 服务器返回了错误响应
              this.errorMessage = error.response.data?.msg || '登录失败，请检查用户名和密码'
            } else {
              this.errorMessage = '登录失败: ' + (error.message || '未知错误')
            }
          }
        } else {
          this.errorMessage = '请填写完整的登录信息'
        }
      } finally {
        this.loading = false;
      }
    },
    handleRegister() {
      // Check if the register route exists before navigating
      const hasRegisterRoute = this.$router.resolve('/register').matched.length > 0;
      if (hasRegisterRoute) {
        this.$router.push('/register')
      } else {
        this.$message.warning('注册功能尚未实现')
      }
    }
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f5f5;
  /* Add vendor prefixes for better cross-browser compatibility */
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  touch-action: manipulation;
  -ms-touch-action: manipulation;
  width: -webkit-fill-available;
  width: stretch;
}

.login-card {
  width: 400px;
  /* Add vendor prefixes for better cross-browser compatibility */
  width: -webkit-fill-available;
  width: stretch;
}

.error-message {
  color: #f56c6c;
  font-size: 14px;
  margin-top: 10px;
  text-align: center;
  /* Add vendor prefixes for better cross-browser compatibility */
  -webkit-user-select: text;
  -moz-user-select: text;
  -ms-user-select: text;
  user-select: text;
}
</style>